package com.own.core.privilege;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.own.core.object.admin.User;
import com.own.core.util.Action;
import com.own.core.object.admin.Role;
import com.own.core.operation.DbOperation;

public class AuthorizationPages {
	User user;
	Map<String, Set<Action>> privMap;

	public AuthorizationPages(User user) {

		this.user = user;

	}

	public boolean haveAuthorization(String PageName, Action action) {

		Set pageAuth;
//		if (privMap == null) {
			privMap = new HashMap<String, Set<Action>>();
			Map paraMap = new HashMap();
			paraMap.put("userId", user.getId());
			List userRole = DbOperation.getME().executeNamedQuery(
					"role.loadAuthPages", paraMap);

			// for roles
			for (Object obj : userRole) {

				Role role = (Role) obj;
				pageAuth = privMap.get(role.getPage().getClassName());

				if (pageAuth == null) {
					pageAuth = new HashSet<Action>();
					privMap.put(role.getPage().getClassName(), pageAuth);
				}
				
				pageAuth.add(role.getAction());

//			}

		}
		pageAuth = privMap.get(PageName);

		if (pageAuth == null) {
			return false;
		}

		return pageAuth.contains(action)||pageAuth.contains(Action.ALL);
	}
}
